package org.soderiakelvy.model.dao.imp;

import java.io.Serializable;
import java.util.List;


import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.soderiakelvy.model.dao.PackDao;
import org.soderiakelvy.model.domain.PackVO;
import org.soderiakelvy.model.util.HibernateUtil;

public class PackDaoImp implements PackDao, Serializable{
	private static final long serialVersionUID = -62446734688952972L;

	@Override
	public void insertPackVO(PackVO pack) throws Exception {
		SessionFactory sessionFacotry = HibernateUtil.getSessionFactory();
		Session session = sessionFacotry.openSession();
		session.beginTransaction();
		session.save(pack);
		session.getTransaction().commit();
		session.close();
		
	}

	@Override
	public void updatePackVO(PackVO pack) throws Exception {
		SessionFactory sessionFacotry = HibernateUtil.getSessionFactory();
		Session session = sessionFacotry.openSession();
		session.beginTransaction();
		session.update(pack);
		session.getTransaction().commit();
		session.close();
		
	}

	@Override
	public void deletePackVO(PackVO pack) throws Exception {
		SessionFactory sessionFacotry = HibernateUtil.getSessionFactory();
		Session session = sessionFacotry.openSession();
		session.beginTransaction();
		session.delete(pack);
		session.getTransaction().commit();
		session.close();
		
	}

	@Override
	public List<PackVO> getAllPacks() throws Exception {
		SessionFactory sessionFacotry = HibernateUtil.getSessionFactory();
		Session session = sessionFacotry.openSession();
		Criteria criteria = session.createCriteria(PackVO.class);
		criteria.addOrder(Order.asc("packId"));
		List<PackVO> packs = criteria.list();
		session.close();
		return packs;
	}

	@Override
	public PackVO getPackById(long id) throws Exception {
		SessionFactory sessionFacotry = HibernateUtil.getSessionFactory();
		Session session = sessionFacotry.openSession();
		Criteria criteria = session.createCriteria(PackVO.class);
		criteria.add(Restrictions.eq("packId", id));
		PackVO packs = (PackVO)criteria.uniqueResult();
		session.close();
		return packs;
	}

	@Override
	public PackVO getPackByNombre(String nombre) throws Exception {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		Criteria criteria = session.createCriteria(PackVO.class);
		criteria.add(Restrictions.eq("nombre", nombre));
		PackVO pVO =(PackVO) criteria.uniqueResult(); 
		session.close();
		return pVO;
	}

}
